<template>
  <div class="dashboard">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-icon" style="background: #409eff">
            <el-icon :size="32"><Folder /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ formatSize(overview.files?.totalSize || 0) }}</div>
            <div class="stat-label">文件总大小</div>
            <div class="stat-desc">{{ overview.files?.totalCount || 0 }} 个文件</div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-icon" style="background: #67c23a">
            <el-icon :size="32"><User /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ overview.users?.onlineCount || 0 }}</div>
            <div class="stat-label">在线用户</div>
            <div class="stat-desc">实时在线</div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-icon" style="background: #e6a23c">
            <el-icon :size="32"><Upload /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ formatSize(overview.today?.uploadSize || 0) }}</div>
            <div class="stat-label">今日上传</div>
            <div class="stat-desc">{{ overview.today?.uploadCount || 0 }} 个任务</div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-icon" style="background: #f56c6c">
            <el-icon :size="32"><Download /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ formatSize(overview.today?.downloadSize || 0) }}</div>
            <div class="stat-label">今日下载</div>
            <div class="stat-desc">{{ overview.today?.downloadCount || 0 }} 个任务</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 系统资源监控 -->
    <el-row :gutter="20" class="monitor-row">
      <el-col :span="8">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>CPU使用率</span>
              <el-tag>{{ overview.system?.cpu?.usage || 0 }}%</el-tag>
            </div>
          </template>
          <el-progress
            :percentage="parseFloat(overview.system?.cpu?.usage || 0)"
            :color="getProgressColor(overview.system?.cpu?.usage)"
          />
          <div class="monitor-info">
            核心数: {{ overview.system?.cpu?.cores || 0 }}
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>内存使用率</span>
              <el-tag>{{ overview.system?.memory?.usage || 0 }}%</el-tag>
            </div>
          </template>
          <el-progress
            :percentage="parseFloat(overview.system?.memory?.usage || 0)"
            :color="getProgressColor(overview.system?.memory?.usage)"
          />
          <div class="monitor-info">
            {{ formatSize(overview.system?.memory?.used || 0) }} / {{ formatSize(overview.system?.memory?.total || 0) }}
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>硬盘使用率</span>
              <el-tag>{{ overview.system?.disk?.usage || 0 }}%</el-tag>
            </div>
          </template>
          <el-progress
            :percentage="parseFloat(overview.system?.disk?.usage || 0)"
            :color="getProgressColor(overview.system?.disk?.usage)"
          />
          <div class="monitor-info">
            {{ formatSize(overview.system?.disk?.used || 0) }} / {{ formatSize(overview.system?.disk?.total || 0) }}
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 网络速度和传输统计 -->
    <el-row :gutter="20" class="monitor-row">
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>网络速度</span>
              <el-tag type="success">实时</el-tag>
            </div>
          </template>
          <div class="network-speed">
            <div class="speed-item">
              <el-icon color="#67c23a"><Upload /></el-icon>
              <span>{{ formatSpeed(overview.system?.network?.uploadSpeed || 0) }}</span>
            </div>
            <div class="speed-item">
              <el-icon color="#409eff"><Download /></el-icon>
              <span>{{ formatSpeed(overview.system?.network?.downloadSpeed || 0) }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>活动传输</span>
              <el-tag type="warning">{{ activeTransfers.length }} 个任务</el-tag>
            </div>
          </template>
          <div class="active-transfers">
            <div v-if="activeTransfers.length === 0" class="empty-transfers">
              <el-icon :size="32" color="#909399"><DocumentCopy /></el-icon>
              <p>暂无传输任务</p>
            </div>
            <div v-else class="transfer-list-mini">
              <div v-for="task in activeTransfers.slice(0, 3)" :key="task.id" class="transfer-mini-item">
                <div class="transfer-mini-info">
                  <el-icon :color="task.type === 'upload' ? '#67c23a' : '#409eff'">
                    <component :is="task.type === 'upload' ? Upload : Download" />
                  </el-icon>
                  <span class="transfer-mini-name">{{ task.file_name }}</span>
                  <span class="transfer-mini-progress">{{ task.progress }}%</span>
                </div>
                <el-progress :percentage="task.progress" :show-text="false" />
              </div>
              <div v-if="activeTransfers.length > 3" class="more-transfers">
                还有 {{ activeTransfers.length - 3 }} 个任务...
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>网络流量趋势</span>
              <el-radio-group v-model="trendDays" size="small" @change="loadNetworkTrend">
                <el-radio-button :label="7">近7天</el-radio-button>
                <el-radio-button :label="30">近30天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="trendChartRef" style="height: 300px"></div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card>
          <template #header>
            <span>文件类型分布</span>
          </template>
          <div ref="fileTypeChartRef" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 地图和在线用户 -->
    <el-row :gutter="20" class="map-row">
      <el-col :span="16">
        <el-card>
          <template #header>
            <span>地域流量分布</span>
          </template>
          <div ref="mapChartRef" style="height: 400px"></div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card>
          <template #header>
            <span>用户排行榜</span>
          </template>
          <el-table :data="userRanking" height="400" size="small">
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="total_uploaded" label="上传量" align="right">
              <template #default="{ row }">
                {{ formatSize(row.total_uploaded) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import api from '@/api'
import { DocumentCopy } from '@element-plus/icons-vue'

const overview = ref({})
const trendDays = ref(7)
const userRanking = ref([])
const activeTransfers = ref([])

const trendChartRef = ref()
const fileTypeChartRef = ref()
const mapChartRef = ref()

let trendChart = null
let fileTypeChart = null
let mapChart = null
let refreshTimer = null

// 加载系统概览
const loadOverview = async () => {
  try {
    const res = await api.get('/api/stats/overview')
    if (res.data.success) {
      overview.value = res.data.data
    }
  } catch (error) {
    console.error('加载系统概览失败:', error)
  }
}

// 加载活动传输列表
const loadActiveTransfers = async () => {
  try {
    const res = await api.get('/api/transfers', {
      params: { 
        status: 'active',
        limit: 10
      }
    })
    if (res.data.success) {
      activeTransfers.value = res.data.data.tasks || []
    }
  } catch (error) {
    console.error('加载活动传输失败:', error)
  }
}

// 加载网络流量趋势
const loadNetworkTrend = async () => {
  try {
    const res = await api.get('/api/stats/network-trend', {
      params: { days: trendDays.value }
    })

    if (res.data.success && trendChart) {
      const data = res.data.data
      trendChart.setOption({
        xAxis: {
          data: data.map(item => item.stat_date)
        },
        series: [
          {
            name: '上传',
            data: data.map(item => (item.upload / 1024 / 1024).toFixed(2))
          },
          {
            name: '下载',
            data: data.map(item => (item.download / 1024 / 1024).toFixed(2))
          }
        ]
      })
    }
  } catch (error) {
    console.error('加载网络流量趋势失败:', error)
  }
}

// 加载文件类型分布
const loadFileTypeStats = async () => {
  try {
    const res = await api.get('/api/stats/file-types')

    if (res.data.success && fileTypeChart) {
      const data = res.data.data
      fileTypeChart.setOption({
        series: [{
          data: data.map(item => ({
            name: item.type,
            value: item.count
          }))
        }]
      })
    }
  } catch (error) {
    console.error('加载文件类型分布失败:', error)
  }
}

// 加载地域流量
const loadLocationStats = async () => {
  try {
    const res = await api.get('/api/stats/location')

    if (res.data.success && mapChart) {
      const data = res.data.data
      const provinces = data.map(item => item.province)
      const values = data.map(item => item.total_bytes)

      mapChart.setOption({
        xAxis: {
          data: provinces
        },
        series: [{
          data: values
        }]
      })
    }
  } catch (error) {
    console.error('加载地域流量失败:', error)
  }
}

// 加载用户排行
const loadUserRanking = async () => {
  try {
    const res = await api.get('/api/stats/user-activity', {
      params: { type: 'upload', limit: 10 }
    })

    if (res.data.success) {
      userRanking.value = res.data.data
    }
  } catch (error) {
    console.error('加载用户排行失败:', error)
  }
}

// 初始化图表
const initCharts = () => {
  // 流量趋势图
  trendChart = echarts.init(trendChartRef.value)
  trendChart.setOption({
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['上传', '下载']
    },
    xAxis: {
      type: 'category',
      boundaryGap: false
    },
    yAxis: {
      type: 'value',
      name: '流量 (MB)'
    },
    series: [
      {
        name: '上传',
        type: 'line',
        smooth: true,
        areaStyle: {},
        color: '#67c23a'
      },
      {
        name: '下载',
        type: 'line',
        smooth: true,
        areaStyle: {},
        color: '#409eff'
      }
    ]
  })

  // 文件类型饼图
  fileTypeChart = echarts.init(fileTypeChartRef.value)
  fileTypeChart.setOption({
    tooltip: {
      trigger: 'item'
    },
    series: [{
      type: 'pie',
      radius: '50%',
      label: {
        formatter: '{b}: {c} ({d}%)'
      }
    }]
  })

  // 地域分布柱状图(替代地图)
  mapChart = echarts.init(mapChartRef.value)
  mapChart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params) => {
        const item = params[0]
        const value = item.value / 1024 / 1024
        return `${item.name}<br/>流量: ${value.toFixed(2)} MB`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: [],
      axisLabel: {
        rotate: 45,
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '流量 (MB)',
      axisLabel: {
        formatter: (value) => {
          return (value / 1024 / 1024).toFixed(0)
        }
      }
    },
    series: [{
      name: '流量',
      type: 'bar',
      data: [],
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#83bff6' },
          { offset: 0.5, color: '#188df0' },
          { offset: 1, color: '#188df0' }
        ])
      },
      emphasis: {
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#2378f7' },
            { offset: 0.7, color: '#2378f7' },
            { offset: 1, color: '#83bff6' }
          ])
        }
      }
    }]
  })
}

// 格式化文件大小
const formatSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i]
}

// 格式化速度
const formatSpeed = (bytesPerSecond) => {
  return formatSize(bytesPerSecond) + '/s'
}

// 获取进度条颜色
const getProgressColor = (percentage) => {
  percentage = parseFloat(percentage)
  if (percentage < 60) return '#67c23a'
  if (percentage < 80) return '#e6a23c'
  return '#f56c6c'
}

// 刷新数据
const refreshData = () => {
  loadOverview()
  loadActiveTransfers()
  loadNetworkTrend()
  loadFileTypeStats()
  loadLocationStats()
  loadUserRanking()
}

onMounted(() => {
  initCharts()
  refreshData()

  // 🔥 每10秒刷新一次
  refreshTimer = setInterval(refreshData, 10000)

  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    trendChart?.resize()
    fileTypeChart?.resize()
    mapChart?.resize()
  })
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }

  trendChart?.dispose()
  fileTypeChart?.dispose()
  mapChart?.dispose()
})
</script>

<style scoped>
.dashboard {
  padding: 0;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
}

.stat-card :deep(.el-card__body) {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 64px;
  height: 64px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-right: 20px;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.stat-desc {
  font-size: 12px;
  color: #c0c4cc;
  margin-top: 3px;
}

.monitor-row,
.chart-row,
.map-row {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.monitor-info {
  margin-top: 10px;
  font-size: 14px;
  color: #606266;
}

.network-speed {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 20px 0;
}

.speed-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.speed-item span {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.active-transfers {
  min-height: 150px;
}

.empty-transfers {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #909399;
}

.empty-transfers p {
  margin-top: 15px;
  font-size: 14px;
}

.transfer-list-mini {
  padding: 10px 0;
}

.transfer-mini-item {
  padding: 10px 15px;
  margin-bottom: 10px;
  background: #f5f7fa;
  border-radius: 6px;
}

.transfer-mini-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  gap: 10px;
}

.transfer-mini-name {
  flex: 1;
  font-size: 13px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.transfer-mini-progress {
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}

.more-transfers {
  text-align: center;
  padding: 10px;
  font-size: 12px;
  color: #909399;
}
</style>
